import router, { asyncRoutes } from '@/router/index.js'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
const whileList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
//   console.log('去哪里?', to)
//   console.log('哪里来?', from)
  // 放行
  NProgress.start() // 开启进度条
  const token = store.state.user.token
  const title = getPageTitle(to.meta.title)
  document.title = title
  // console.log(document,'document')

  // document.title = `人力资源管理平台 - ${to.meta.title}`
  if (token) {
    console.log('你登录了')
    if (to.path === '/login') {
      console.log('你登录了,滚回去吧')
      next('/')
      NProgress.done() // 关闭进度条
    } else {
      if (!store.getters.userId) {
        const menus = await store.dispatch('user/getUserInfo')
        // console.log(menus, 'menussssssssssssssss')
        // console.log(asyncRoutes, 'asyncRoutes')
        const filterRouters = asyncRoutes.filter(router => {
          return menus.includes(router.children[0].name)
        })
        // 404 page must be placed at the end !!  在路由末尾添加* 404
        filterRouters.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRouters)
        // 存入vuex
        store.commit('menu/updateRouters', filterRouters)
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
      }

      console.log('放行')
      next()
    }
  } else {
    if (whileList.includes(to.path)) {
      console.log('怪')
      next()
    } else {
      console.log('滚去登录')
      next('/login')
      NProgress.done() // 关闭进度条
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 关闭进度条
})
